#!/usr/bin/env python3
import sys
if sys.version_info < (3, 5):
    sys.exit("Python 3.5 or later is required")

import pathlib
import re

if len(sys.argv) != 3:
    sys.exit("Expected exactly 2 arguments:" +
             " src/path/to/GENCADFileBnf.h" +
             " build/path/to/build-generated/GENCADFileGrammar.h")

src_path = pathlib.Path(sys.argv[1])
src_text_filtered = "\n".join(line for line
                              in src_path.read_text().split("\n")
                              if "SKIP_LINE_IN_GRAMMAR_GENERATOR" not in line)
rules = [spaces_and_rule.strip()
         for spaces_and_rule
         in re.findall(r"^\s*\w+", src_text_filtered, re.MULTILINE)]

if len(rules) < 1:
    sys.exit("Input file " + str(src_path) +
             " doesn't contain rules in format like below:\n" +
             "rule_name    : (any rule definition after colon until new line)")

out_text = """#pragma once
/**
 *********************************************************************************
 *********************************************************************************
  WARNING THIS IS BUILD-TIME AUTOGENERATED FILE!!!
  Do not modify this file, but edit the source data """ + src_path.name + """
  or generator script """ + pathlib.Path(__file__).name + """
 *********************************************************************************
 *********************************************************************************
 **/
#define X_MACRO_PARSE_VARS \
"""
for rule in rules:
    out_text += 'X({0}, "{0}")\\\n'.format(rule)
out_text += " /*'empty' line to end last continuation*/\n"

out_path = pathlib.Path(sys.argv[2])
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(out_text)
